<?php
namespace common\forms\login;

use Yii;
use yii\base\Model;
use yii\base\ModelEvent;
use yii\base\NotSupportedException;

/**
 * 登录基础
 */
class BaseLoginForm extends Model
{
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
    const EVENT_AFTER_LOGIN = 'afterLogin';

    public $loginTokenType = 'kv';

    protected function loginResult($userIdentity){
        $loginToken = '';
        $accessAuthorizationName = '';
        switch($this->loginTokenType){
            case 'jwt':
                //TODO
                throw new NotSupportedException('jwt模式开发中...');
                break;
            default:
                $session = Yii::$app->getSession();
                $loginToken = $session->getId();
                $accessAuthorizationName = $session->getName();
                break;
        }

        return [
            'login_token' => $loginToken,
            'login_token_type'=> $this->loginTokenType,
            'access_authorization_name' => $accessAuthorizationName,
            'identity' => $userIdentity];
    }

    /**
     * 
     */
    public function beforeLogin()
    {
        $event = new ModelEvent;
        $this->trigger(self::EVENT_BEFORE_LOGIN, $event);

        return $event->isValid;
    }

    /**
     * 
     */
    public function afterLogin()
    {
        $this->trigger(self::EVENT_AFTER_LOGIN);
    }

    public function getUserIdentity()
    {
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
    }

    /**
     * 会员登陆.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function login()
    {
        $this->beforeLogin();
        if(!$this->validate()){
            return null;
        }
        $userIdentity = $this->getUserIdentity();
        if(!$userIdentity){
            return null;
        }
        Yii::$app->getUser()->login($userIdentity);
        $this->afterLogin();
        return $this->loginResult($userIdentity);
    }

    

    /**
     * 登陆通过ID.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function loginIdentity($id)
    {
        $userClassName = Yii::$app->getUser()->identityClass;
        $this->_user = $userClassName::findIdentity($id);
        if (!$this->beforeLogin()) {
            return false;
        }
        return $this->_user;
    }
}
